package com.fe.class04;

import java.util.Arrays;

/**
 * @Description 递归方式实现归并排序
 * @Author sosuke :-)
 * @Date 2021/12/13 06:48
 */
public class Code01_MergeSort_Recursion {

    public static void mergeSort(int[] arr) {
        if (null == arr || arr.length < 2) return;
        process(arr, 0, arr.length - 1);
    }

    /**
     * 请把arr[L..R]排有序
     * T(N) = 2 * T(N / 2) + O(N)
     * O(N * logN)
     * @param arr
     * @param L
     * @param R
     */
    private static void process(int[] arr, int L, int R) {
        if (L > R) {
            throw new RuntimeException("参数错误");
        }
        if (L == R) { // base case
            return;
        }
        int mid = L + ((R - L) >> 1);
        process(arr, L, mid);
        process(arr, mid + 1, R);
        merge(arr, L, mid, R);
    }

    /**
     * 合并操作
     * @param arr
     * @param L
     * @param M
     * @param R
     */
    private static void merge(int[] arr, int L, int M, int R) {
        int len = R - L + 1;
        int[] help = new int[len];
        int i = 0;
        int p1 = L;
        int p2 = M + 1;
        // 都没有越界的情况下，谁小拷贝谁，相等则先拷贝左组
        while (p1 <= M && p2 <= R) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        // 要么p1越界了，要么p2越界了
        while (p1 <= M) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }
        // 将排好序的辅助数组拷贝到arr
        // System.arraycopy(help, 0, arr, L, help.length);
        for (i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
    }

    public static void main(String[] args) {
        int testTime = 100000; // 测试次数
        int maxSize = 10; // 数组数据个数
        int maxValue = 200; // 数组中最大值
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize, maxValue);
            int[] arr2 = Arrays.copyOf(arr1, arr1.length);
            mergeSort(arr1);
            Arrays.sort(arr2);
            if (!Arrays.equals(arr1, arr2)) {
                System.out.println("Fuck");
                System.out.println(Arrays.toString(arr1));
                System.out.println(Arrays.toString(arr2));
                return;
            }
        }
        System.out.println("Nice");
        int[] arr = generateRandomArray(maxSize, maxValue);
        System.out.println(Arrays.toString(arr));
        mergeSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) ((maxValue + 1) * Math.random());
        }
        return arr;
    }

}
